package com.witframework.web.file;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.witframework.web.util.DownLoadFileHelper;

/**
 * 文件下载辅助处理类,将二进制文件流输出到客户端<p>
 * 用法如下：<code><pre>
 * DownloadHelper dl=new DownloadHelper(request, response);
 * java.io.ByteArrayInputStream is=new java.io.ByteArrayInputStream("fuck you".getBytes());
 * dl.outToClient("数据.txt",null,true,is);</pre>
 *</code>
 * 需要确保在输出流内容时，未在ServletResponse上执行getWriter()或getOutputStream（）方法。
 * 因此正确的调用是在只处理下载的serlvet中。
 * @author wuxinyang
 *
 */
public class DownloadHelper{
	private HttpServletRequest request;
	private HttpServletResponse response;
	public DownloadHelper(HttpServletRequest request, HttpServletResponse response){
		this.request=request;
		this.response=response;
	}
	/**
	 * 输出流到客户端
	 * @param fileName 文件名称
	 * @param is 输入流
	 * @see #outToClient(String, String, boolean, InputStream)
	 */
	public void outToClient(String fileName,InputStream is){
		outToClient(fileName,"UTF-8",false,is);
	}
	/**
	 * 输出流到客户端
	 * @param fileName 文件名称
	 * @param charset 字符编码 默认编码为"UTF-8"
	 * @param isShowInExperlor 是否直接在浏览器中打开，默认值为flase。
	 * 	如果设为true，则输出内容将直接在浏览器中显示，通常用于图片类型的内容。
	 * @param is 输入流
	 */
	public void outToClient(String fileName,String charset,boolean isShowInExperlor,InputStream is){
		try {
			if (null == charset) {
				charset = request.getCharacterEncoding();
			}
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int byteLength = 0;
			byte[] content=new byte[1024];
			while ((byteLength = is.read(content)) > 0) {
				baos.write(content,0,byteLength);
			}
			is.close();
			// 设置参数
			response.reset();
			String strContentTemp = "attachment;";
			if (isShowInExperlor) {
				strContentTemp = "inline;";
			}
			if (null != charset) {
				String strFileNameTemp = new String(fileName.getBytes(),"UTF-8");
				strContentTemp = strContentTemp + "filename=" + strFileNameTemp;
			} else {
				strContentTemp = strContentTemp + "filename=" + fileName;
			}
			String  mimeType=new DownLoadFileHelper().getMimeTypeFromFileName(fileName);
		      if (null == mimeType) {
		    	  mimeType = "charset=" + charset;
		      }
		      else {
		    	  mimeType = mimeType + ";charset=" + charset;
		      }
			response.setContentType(mimeType);
			response.setHeader("Content-Disposition", strContentTemp);
			response.setContentLength(baos.size());
			// 写到浏览器
			OutputStream os = response.getOutputStream();
			baos.flush();
			os.write(baos.toByteArray());
			baos.close();
			os.flush();
			os.close();
		} catch (Exception e) {
			throw new FileDownloadException("下载处理出错。",e);
		}
	}
}
